package com.linghang.wusthelper.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.linghang.wusthelper.entity.primary.Student;

import java.util.Date;

/**
 * @author origin
 * JWT认证工具类
 */
public class JWTUtil {

    public static String createToken(Student student){
        Date now  = new Date();
        String secret = student.getUUID();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        String token = JWT.create()
                .withIssuer("lhstudio")
                .withAudience("wusthelper")
                .withClaim("stuNum",student.getStuNum())
                .withIssuedAt(now)
                .sign(algorithm);
        return token;
    }

    public static boolean requireToken(String token,Student student){
        String secret = student.getUUID();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withIssuer("lhstudio")
                .build();
        try{
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            return false;
        }
        return true;
    }

}
